<?php
class HomeController extends Zend_Controller_Action
{
	protected $_acl;
	protected $_userGroup;
	
	public function init()
	{
		$auth = Zend_Auth::getInstance();
		$userInfo = $auth->getStorage()->read();
		$groupBase = new GroupBase();
		if ($userInfo) {
			$userGroups = $groupBase->getUserGroup($userInfo->name);
		}
		$this->_userGroup = $userGroups[0]['name'] ? $userGroups[0]['name'] : "Users";
		$this->_acl = new Acl_PPMIS();
		$this->view->acl = $this->_acl;
		$this->view->userGroup = $this->_userGroup;
	}
	
	
	public function preDispatch()
	{
		$this->view->inc_yui = true;
		$auth = Zend_Auth::getInstance();
		if($auth->getIdentity()) {
			$userInfo = $auth->getStorage()->read();
			$this->view->userInfo = $userInfo;
		} else {
			$this->_redirect('auth/login');
		}
		$Configuration = new Configuration();
		$configurationData = $Configuration->getConfigurationInfo();
		$this->view->configuration = $configurationData;
		$this->view->current = "home";
	}
	
	public function indexAction()
	{
		$auth = Zend_Auth::getInstance();
		$storage = $auth->getStorage();
		$userInfo = $storage->read();
		//Zend_Debug::dump($userInfo);
		$issue = new Issue();
		$project = new Project();
		$projectData = $project->getAdapter()->fetchAll($project->select());
		//echo $userInfo->fullname;
		
		$searchRequest = new SearchRequest();
		$filterData = $searchRequest->getAdapter()->fetchAll($searchRequest->select());
		$i = 0;
		foreach ($filterData as $data) {
			$sParams = $this->_processXml($data['reqcontent']);
			$where = $this->_buildWhere($sParams);
			$filterData[$i]['c'] = $issue->getIssuesCount($where);
			$i++;
		}
		
		$data = $issue->getAdapter()->fetchAll($issue->select()->where('assignee = ?',$userInfo->fullname));
		$userIssues = $issue->getIssuesByUser($userInfo->fullname);
		$paginator1 = Zend_Paginator::factory($userIssues);
		$paginator1->setItemCountPerPage(10);
		$paginator1->setCurrentPageNumber(1);	
		
		$issuesInProgress = $issue->getIssuesInProgress($userInfo->fullname);
		//Zend_Debug::dump($issuesInProgress);
		$this->view->totalUserIssues = count($userIssues);
		$this->view->totalInprogressIssues = count($issuesInProgress);
		$this->view->displayIssues = (count($userIssues) < 10) ? count($userIssues) : 10;
		$this->view->auth = 'Success';
		$this->view->userIssues = $paginator1;
		$this->view->issuesInProgress = $issuesInProgress;
		$this->view->displayProgressIssues = (count($issuesInProgress) < 10) ? count($issuesInProgress) : 10;
		$this->view->projectData = $projectData;
		$this->view->filterData = $filterData;
		//Zend_Debug::dump($projectData);
	}
	
	protected function _processXml($data)
	{
		$objReader = XMLReader::XML($data);
			$params = array();
				while ($objReader->read()) {
					if($objReader->nodeType == 1 && $objReader->localName == 'project' && $objReader->hasAttributes) {
						$params['projects'][] = $objReader->getAttribute('id');
					}
					if($objReader->nodeType == 1 && $objReader->localName == 'issuetype' && $objReader->hasAttributes) {
						$params['issuetypes'][] = $objReader->getAttribute('value');
					}
					if($objReader->nodeType == 1 && $objReader->localName == 'query') {
						$query = $objReader->readString();
						$params['query']['text'] = $query;
						if($objReader->getAttribute['summary']) {
							$params['query']['summary'] = true;
						}
						if($objReader->getAttribute['description']) {
							$params['query']['description'] = true;
						}
						if($objReader->getAttribute['comments']) {
							$params['query']['comments'] = true;
						}
						if($objReader->getAttribute['environment']) {
							$params['query']['environment'] = true;
						}
					}
					
					if($objReader->nodeType == 1 && $objReader->localName == 'reporter' && $objReader->hasAttributes) {
						$params['reporter'] = $objReader->getAttribute('key');
						if ($params['reporter'] == 'specify') {
							$params['reporterName'] = $objReader->readString();
						}
					
					}
					if($objReader->nodeType == 1 && $objReader->localName == 'assignee' && $objReader->hasAttributes) {
						$params['assignee'] = $objReader->getAttribute('key');
						if ($params['assignee'] == 'specify') {
							$params['assigneeName'] = $objReader->readString();
						}
					
					}
					
					if($objReader->nodeType == 1 && $objReader->localName == 'issuestatus' && $objReader->hasAttributes) {
						$params['statuses'][] = $objReader->getAttribute('value');
					}
					if($objReader->nodeType == 1 && $objReader->localName == 'resolution' && $objReader->hasAttributes) {
						$params['resolutions'][] = $objReader->getAttribute('value');
					}
					if($objReader->nodeType == 1 && $objReader->localName == 'priority' && $objReader->hasAttributes) {
						$params['priorities'][] = $objReader->getAttribute('value');
					}
					if($objReader->nodeType == 1 && $objReader->localName == 'created' && $objReader->hasAttributes) {
						if ($objReader->getAttribute('after')) {
							$params['createdAfter'] = $objReader->getAttribute('after');
						}
						if ($objReader->getAttribute('before')) {
							$params['createdBefore'] = $objReader->getAttribute('before');
						}
					}
					if($objReader->nodeType == 1 && $objReader->localName == 'updated' && $objReader->hasAttributes) {
						if ($objReader->getAttribute('after')) {
							$params['updatedAfter'] = $objReader->getAttribute('after');
						}
						if ($objReader->getAttribute('before')) {
							$params['updatedBefore'] = $objReader->getAttribute('before');
						}
					}
					if($objReader->nodeType == 1 && $objReader->localName == 'duedate' && $objReader->hasAttributes) {
						if ($objReader->getAttribute('after')) {
							$params['duedateAfter'] = $objReader->getAttribute('after');
						}
						if ($objReader->getAttribute('before')) {
							$params['duedateBefore'] = $objReader->getAttribute('before');
						}
					}
			}
		return $params;
	}

	
	protected function _buildWhere($params)
	{
		$where = "1=1";
		$i = 0;
		for($i = 0 ; $i < count($params['projects']); $i++) {
			if ($i == 0) {
				$where .= " AND (";
			}
			$where .= "project = ". $params['projects'][$i];
			if($params['projects'][$i+1]) {
				$where .= " OR ";
			} else {
				$where .= ')';
			}
		}
		
		$i = 0;
		for($i = 0 ; $i < count($params['issuetypes']); $i++) {
			if ($i == 0) {
				$where .= " AND (";
			}
			$where .= "issuetype = ". $params['issuetypes'][$i];
			if($params['issuetypes'][$i+1]) {
				$where .= " OR ";
			} else {
				$where .= ')';
			}
		}
		
		if($params['reporter']) {
			if($params['reporter'] == 'any') {
			
			} elseif ($params['reporter'] == 'no') {
				$where .= " AND issue.reporter = ''";
			} elseif ($params['reporter'] == 'current') {
				$auth = Zend_Auth::getInstance();
				if($auth->getIdentity()) {
					$userInfo = $auth->getStorage()->read();
					$where .= " AND issue.reporter = '".$userInfo->fullname."'";
				}
			} elseif ($params['reporter'] == 'specify' && isset($params['reporterName'])) {
				$where .= " AND issue.reporter = '".$params['reporterName']."'";
			}
		}
		
		if($params['assignee']) {
			if($params['assignee'] == 'any') {
			
			} elseif ($params['assignee'] == 'no') {
				$where .= " AND issue.assignee = ''";
			} elseif ($params['assignee'] == 'current') {
				$auth = Zend_Auth::getInstance();
				if($auth->getIdentity()) {
					$userInfo = $auth->getStorage()->read();
					$where .= " AND issue.assignee = '".$userInfo->fullname."'";
				}
			} elseif ($params['assignee'] == 'specify' && isset($params['assigneeName'])) {
				$where .= " AND issue.assignee = '".$params['assigneeName']."'";
			}
		}
		
		$i = 0;
		for($i = 0 ; $i < count($params['fixVersions']); $i++) {
			if ($i == 0) {
				$where .= " AND (";
			}
			$where .= "issue.id IN (SELECT source_node_id FROM nodeassociation where association_type ='IssueFixVersion' AND sink_node_id = ". $params['fixVersions'][$i].")";
			if($params['fixVersions'][$i+1]) {
				$where .= " OR ";
			} else {
				$where .= ')';
			}
		}
		
		
		$i = 0;
		for($i = 0 ; $i < count($params['components']); $i++) {
			if ($i == 0) {
				$where .= " AND (";
			}
			$where .= "issue.id IN (SELECT source_node_id FROM nodeassociation where association_type ='IssueComponent' AND sink_node_id = ". $params['components'][$i].")";
			if($params['components'][$i+1]) {
				$where .= " OR ";
			} else {
				$where .= ')';
			}
		}
		
		$i = 0;
		for($i = 0 ; $i < count($params['affectVersions']); $i++) {
			if ($i == 0) {
				$where .= " AND (";
			}
			$where .= "issue.id IN (SELECT source_node_id FROM nodeassociation where association_type ='IssueVersion' AND sink_node_id = ". $params['affectVersions'][$i].")";
			if($params['affectVersions'][$i+1]) {
				$where .= " OR ";
			} else {
				$where .= ')';
			}
		}
		
		
		//Zend_Debug::dump($params);
		if($params['query']['text'] != '') {
			$flag = false;
			$where .= " AND (";
			if($params['query']['summary']) {
				$where .= "summary like '%". $params['query']['text']."%'";
				$flag = true;
			}
			if($params['query']['description']) {
				if($flag) {
					$where .= " OR ";
				}
				$where .= "issue.description like '%". $params['query']['text']."%'";
				$flag = true;
			}
			if($params['query']['comments']) {
				if($flag) {
					$where .= " OR ";
				}
				$where .= "issue.id IN (SELECT issueid from action where action_type = 'comment' AND action_body like '%".$params['query']['text']."%')";
				$flag = true;
			}
			/*if($params['query']['description']) {
				if($flag) {
					$where .= " OR ";
				}
				$where .= "description =". $params['query']['description'];
				$flag = true;
			}*/
			if ($flag == false) {
				$where .= "summary like '%". $params['query']['text']."%'";
				$where .= " OR issue.description like '%". $params['query']['text']."%'";
				$where .= " OR issue.id IN (SELECT issueid from action where action_type = 'comment' AND action_body like '%".$params['query']['text']."%')";
				//$where .= "summary =". $params['query']['summary'];
				//$where .= "summary =". $params['query']['summary'];
			}
			$where .= ")";
		}
		
		$i = 0;
		for($i = 0 ; $i < count($params['statuses']); $i++) {
			if ($i == 0) {
				$where .= " AND (";
			}
			$where .= "issuestatus = ". $params['statuses'][$i];
			if($params['statuses'][$i+1]) {
				$where .= " OR ";
			} else {
				$where .= ')';
			}
		}
		
		$i = 0;
		for($i = 0 ; $i < count($params['resolutions']); $i++) {
			if ($i == 0) {
				$where .= " AND (";
			}
			$where .= "resolution = ". $params['resolutions'][$i];
			if($params['resolutions'][$i+1]) {
				$where .= " OR ";
			} else {
				$where .= ')';
			}
		}
		
		$i = 0;
		for($i = 0 ; $i < count($params['priorities']); $i++) {
			if ($i == 0) {
				$where .= " AND (";
			}
			$where .= "priority = ". $params['priorities'][$i];
			if($params['priorities'][$i+1]) {
				$where .= " OR ";
			} else {
				$where .= ')';
			}
		}
		
		if ($params['createdAfter']) {
			$where .= " AND created > '".date('Y-m-d',strtotime($params['createdAfter']))."'";
		}
		
		if ($params['createdBefore']) {
			$where .= " AND created < '".date('Y-m-d',strtotime($params['createdBefore']))."'";
		}
		
		if ($params['createdPrevious']) {
			//$where .= "";
		}
		if($params['createdNext']) {
		
		}
		
		if ($params['updatedAfter']) {
			$where .= " AND updated > '".date('Y-m-d',strtotime($params['updatedAfter']))."'";
		}
		
		if ($params['updatedBefore']) {
			$where .= " AND updated < '".date('Y-m-d',strtotime($params['updatedBefore']))."'";
		}
		
		if ($params['updatedPrevious']) {
			//$where .= "";
		}
		if($params['updatedNext']) {
		
		}
		
		if ($params['duedateAfter']) {
			$where .= " AND duedate > '".date('Y-m-d',strtotime($params['duedateAfter']))."'";
		}
		
		if ($params['duedateBefore']) {
			$where .= " AND duedate < '".date('Y-m-d',strtotime($params['duedateBefore']))."'";
		}
		
		if ($params['duedatePrevious']) {
			//$where .= "";
		}
		if($params['duedateNext']) {
		
		}
		//echo $where;exit;
		return $where;
	}
	
}